from typing import Annotated

import cv2
from fastapi import APIRouter, UploadFile, Depends, Response
from loguru import logger

from app.dependencies import get_inference
from app.internal.inference import Inference

router = APIRouter(prefix="/inference", tags=["inference"])


@router.post("/best_0809")
async def inference_best_0809(
    file: UploadFile, inference: Annotated[Inference, Depends(get_inference)]
):
    logger.info(
        "Receive inference request with filename: {} and file type: {}",
        file.filename,
        file.content_type,
    )

    try:
        handle = inference.submit_task(file)
        result = handle.wait_result()[0]
        content = result.plot()
        content = cv2.imencode(f".{file.filename.split('.')[-1]}", content)[1].tobytes()  # type: ignore

        return Response(
            content=content,
            media_type="application/octet-stream",
            headers={"Content-Disposition": f'attachment; filename="{file.filename}"'},
        )
    except Exception as e:
        logger.warning(f"Error during inference: {e}")
        return {"error": str(e)}, 500
